package deibay.client.core;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import deibay.client.BidderController;
import deibay.client.IModel;
import deibay.client.ItemObject;
import deibay.client.core.views.IPanelBidder;
import deibay.messages.BiddingItemMsg;
import deibay.messages.RequestItemDetailsMsg;
import deibay.messages.SubscribeItemMsg;

public class DeibayBidderController extends BidderController{
	
	public DeibayBidderController(IPanelBidder view, IModel model) {
		super(view, model);
	}

	@Override
	public void createViewEvents() {
		view.setChangeItemAction(new ListSelectionListener(){

			public void valueChanged(ListSelectionEvent arg0) {				
				selectedItem = (ItemObject)((JList)arg0.getSource()).getSelectedValue();				
			}
			
		});								
		
		view.setClickItemAction(new MouseListener(){

			public void mouseClicked(MouseEvent arg0) {				
				if(arg0.getClickCount() == 2)
				{
					if(selectedItem != null)
					{					
						RequestItemDetailsMsg msg = new RequestItemDetailsMsg(RequestItemDetailsMsg.class.getSimpleName(), (String)selectedItem.getItemId());						
						model.sendMessage(msg);
					}
				}
			}

			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			public void mouseExited(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			public void mousePressed(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			public void mouseReleased(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		getViewItemDetails().setBiddingItemAction(new ActionListener(){

			public void actionPerformed(ActionEvent arg0) {
				if(getViewItemDetails().getActualPrice()>=getViewItemDetails().getStartPrice())
				{
					String id = getViewItemDetails().getID();
					int value = getViewItemDetails().getActualPrice();
					BiddingItemMsg msg = new BiddingItemMsg(BiddingItemMsg.class.getSimpleName(), id, value);
					model.sendMessage(msg);
				}
				else
				{
					JOptionPane.showMessageDialog(null, "O valor da licitacao tem de ser superior que o valor inicial do produto.", "Licitacao", 1);
				}
			}
			
		});
		
		getViewItemDetails().setNotifyItemAction(new ActionListener(){

			public void actionPerformed(ActionEvent arg0) {
				SubscribeItemMsg msg = new SubscribeItemMsg(SubscribeItemMsg.class.getSimpleName(), getViewItemDetails().getID());
				model.sendMessage(msg);
			}
			
		});
				
	}

	@Override
	public void initView() {
		this.viewItemDetails = this.view.showItemDetailsView();
	}
}
